<template>
    <el-dialog :title="`${courierItem._id ? '修改' : '新增'}配送员`" v-model="open" width="500px">
        <el-form label-width="auto" :model="courierItem">
            <el-form-item label="配送员头像">
                <el-upload class="avatar-uploader" 
                    action="http://nocat.life:3011/images/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <User />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="配送员名称">
                <el-input v-model="courierItem.name"></el-input>
            </el-form-item>
            <el-form-item label="手机号码">
                <el-input v-model="courierItem.phone"></el-input>
            </el-form-item>
            <el-form-item label="配送员状态">
                <el-radio-group v-model="courierItem.state">
                    <el-radio :value="1">显示</el-radio>
                    <el-radio :value="0">隐藏</el-radio>
                </el-radio-group>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="open = false">取消</el-button>
            <el-button type="primary" @click="handleOk">确认</el-button>
        </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from 'vue';
import api from '../../api';
import { ElMessage } from 'element-plus';
import { User } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'

const imageUrl = ref('')

// 配送员弹窗的状态
const open = ref(true);

const courierItem = ref({
    _id: '',
    name: '',
    avatar: '',
    phone: '',
    state: 1,
});

const emit = defineEmits(['getCouriersData'])


// 打开弹窗
const openDialog = (data?: any) => {
    if (data) {
        // 进入if，则说明父组件传递了数据（说明当前是在做修改）
        courierItem.value = { ...data };
    }
    open.value = true;
}

const handleOk = () => {
    if (courierItem.value._id) {
        handleUpdate();
    } else {
        handleAdd();
    }
}

const handleAdd = () => {
    console.log('准备新增的配送员数据', courierItem.value);

    const addItem: any = { ...courierItem.value };
    delete addItem._id;

    api.couriers.add(addItem)
        .then(res => {
            console.log(res);
        })
}

const handleUpdate = async () => {
    const res = await api.couriers.update({
        ...courierItem.value
    });
    if (res.code == 200) {
        ElMessage.success('配送员信息修改成功');
        open.value = false;
        // 重新发送请求获取列表的最新数据（调用父组件的自定义事件）
        emit('getCouriersData');
    } else {
        ElMessage.error(res.message);
    }
}


// 在图片上传成功后执行的方法
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    if (response.code == 200) {
        // 将上传成功的图片路径保存到数据中
        courierItem.value.avatar = response.data;
    }
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}
// 在图片上传前，对图片的格式和大小进行验证
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}





// 子组件将openDialog暴露给父组件调用
defineExpose({
    openDialog
})


</script>


<style scoped>
.avatar-uploader .avatar {
    width: 100px;
    height: 100px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    text-align: center;
}
</style>